﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using Ataric.SuppressWP;
using Ataric.SuppressWP.Utilities;
using Ataric.SuppressWP.Model;
using System.Reflection;
using System.Web.UI;

namespace Ataric.SuppressWP
{
    public class SuppressItemsEditorPart : EditorPart
    {
        #region Controls
        private DropDownList ddlGroup;
        private ListBox lstSelectedItems;
        private DropDownList ddlItems;
        private Button btnSelect;
        private Button btnRemove;
        private Image imgPreview;
        private Literal lrtError;
        #endregion

        #region Properties & Variables
        private SuppressSettings _setting;

        public SuppressSettings Settings
        {
            get
            {
                if (_setting != null) return _setting;
                string source = CommonHelper.LoadResource("Ataric.SuppressWP.SuppressWP", "SuppressItems.xml");
                _setting = SerializationHelper.XmlDeserialize<SuppressSettings>(source);
                return _setting;

            }
        } 
        #endregion

        public SuppressItemsEditorPart()
        {
            this.ID = "SuppressItemsEditorPart";
            this.Title = "SuppressME - Ataric.com";

        }

        private void InitControls()
        {
            lrtError = new Literal() { 
                ID ="Error_"+ ID,
                Visible = false,
                EnableViewState = false
            };
            
            imgPreview = new Image()
            {
                ID = "imgPreview_" + ID,

                Visible = false
            };

            ddlGroup = new DropDownList()
            {
                ID = "ddlGroup_" + ID,
                AutoPostBack = true,
                Width = 180,
            };
            ddlGroup.SelectedIndexChanged += new EventHandler(ddlGroup_SelectedIndexChanged);
            ddlItems = new DropDownList()
            {
                ID = "ddlItems_" + ID,
                Width = 180,
                AutoPostBack = true
            };

            ddlItems.SelectedIndexChanged += new EventHandler(ddlItems_SelectedIndexChanged);
            ddlItems.Items.Add(new ListItem() { Text = "Select Item", Value = "" });
            lstSelectedItems = new ListBox()
            {
                Rows = 6,
                ID = "lstSelectedItems_" + ID,
                Width = 180,
                SelectionMode= ListSelectionMode.Multiple
            };
            btnSelect = new Button()
            {
                ID = "btnSelect_" + ID,
                Text="Add",
                Width= 70,
                CssClass = "UserButton"
            };
            
            btnSelect.Click += new EventHandler(btnSelect_Click);
            btnRemove = new Button()
            {
                ID = "btnRemove_" + ID,
                Text="Remove",
                Width = 70,
                CssClass = "UserButton"
            };
            btnRemove.Click += new EventHandler(btnRemove_Click);
                ddlGroup.DataSource = Settings.OrderBy(p=>p.Name);
                ddlGroup.DataTextField = "Name";
                ddlGroup.DataValueField = "Name";
                ddlGroup.DataBind();

                ddlGroup.Items.Insert(0, new ListItem() { Text = "Select Group", Value = "" });

            
        }

        #region Events Handler
        void ddlItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnsureChildControls();
            ShowPreviewImage();
        }

        private void ShowPreviewImage()
        {
            SuppressItem item = Settings[ddlItems.SelectedValue];
            if (item != null && !string.IsNullOrEmpty(item.Image))
            {
                imgPreview.ImageUrl = string.Format("data:image/jpg;base64,{0}", item.Image);
                imgPreview.Visible = true;
            }
            else
            {
                imgPreview.Visible = false;
            }
        }

        void btnRemove_Click(object sender, EventArgs e)
        {
            EnsureChildControls();
            int removed = 0;
            ListItem item = null;
            do
            {
                item = lstSelectedItems.Items.Cast<ListItem>().Where(p => p.Selected).FirstOrDefault();
                if (item != null)
                {
                    lstSelectedItems.Items.Remove(item);
                    removed++;
                }
            }
            while (item != null);
            if (removed == 0)
            {
                lrtError.Text = "No item selected.";
                lrtError.Visible = true;
            }
            else
            {
                RebindItemOnGroupChange();
            }
        }
        void ShowErrorMessage()
        {
            if (ddlItems.Items.Count == 1)
            {
                lrtError.Text = "No more item";
                lrtError.Visible = true;
                btnSelect.Enabled = false;
                btnSelect.Attributes.Add("readonly", "readonly");
            }
            else
            {
                btnSelect.Enabled = true;
                btnSelect.Attributes.Remove("readonly");
            }
        }
        void btnSelect_Click(object sender, EventArgs e)
        {
            EnsureChildControls();
            if (string.IsNullOrEmpty(ddlItems.SelectedItem.Value)) {
                lrtError.Text = "Please select an item.";
                lrtError.Visible = true;
                return;
            };

            if (lstSelectedItems.Items.FindByValue(ddlItems.SelectedItem.Value) == null)
            {

                lstSelectedItems.Items.Add(ddlItems.SelectedItem.Value);
                lstSelectedItems.Items[lstSelectedItems.Items.Count - 1].Selected = true;
                ddlItems.Items.Remove(ddlItems.SelectedItem);
                ddlItems.Items[ddlItems.Items.Count>1?1:0].Selected = true;
                ShowPreviewImage();
            }
            ShowErrorMessage();
        }

        void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            RebindItemOnGroupChange();
        }

        private void RebindItemOnGroupChange()
        {
            if (string.IsNullOrEmpty(ddlGroup.SelectedValue)) return;
            var items = Settings
                            .Where(p => p.Name == ddlGroup.SelectedValue)
                            .OrderBy(p => p.Name)
                            .FirstOrDefault();
            var dataSource = items.SuppressItems.Where(p => !lstSelectedItems.Items.Cast<ListItem>().Any(s => s.Value == p.Name)).ToList();
            ddlItems.DataSource = dataSource;
            ddlItems.DataTextField = "Name";
            ddlItems.DataValueField = "Name";
            ddlItems.DataBind();
            ddlItems.Items.Insert(0, new ListItem() { Text = "Select Item", Value = "" });
            ShowErrorMessage();
            imgPreview.Visible = false;
        }

        #endregion

        #region Override Methods
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //base.EnsureChildControls();
        }

        protected override void CreateChildControls()
        {
            Panel ControlPanel = new Panel();
            InitControls();

            var panel = new UpdatePanel { ID = ID + "UpdatePanel" };
            panel.ContentTemplateContainer.Controls.Add(
            new LiteralControl(@"<table cellspacing=""0"" border=""0""
                style=""border-width:0px;width:100%;
                border-collapse:collapse;""><tr><td>
                <div class=""UserSectionHead"">"));


            //panel.ContentTemplateContainer.Controls.Add(
            //    new LiteralControl(@"Group:<br/>"));
            panel.ContentTemplateContainer.Controls.Add(ddlGroup);
            panel.ContentTemplateContainer.Controls.Add(
                new LiteralControl(@"</div></td></tr>
                <tr><td>
                <div style=""width:100%"" class=""UserDottedLine"">
                </div></td></tr><tr><td>
                <div class=""UserSectionHead"">"));


            //panel.ContentTemplateContainer.Controls.Add(
            //    new LiteralControl(@"Select Items:<br/>"));
            panel.ContentTemplateContainer.Controls.Add(ddlItems);
            panel.ContentTemplateContainer.Controls.Add(new LiteralControl(@"<br/>"));
            panel.ContentTemplateContainer.Controls.Add(imgPreview);
            panel.ContentTemplateContainer.Controls.Add(
                new LiteralControl(@"</div></td></tr>
                <tr><td>
                <div style=""width:100%"" class=""UserDottedLine"">
                </div></td></tr><tr><td>
                <div class=""UserSectionHead"">"));
            panel.ContentTemplateContainer.Controls.Add(new LiteralControl(@"<span class='ms-error'>"));
            panel.ContentTemplateContainer.Controls.Add(lrtError);

            panel.ContentTemplateContainer.Controls.Add(new LiteralControl(@"</span><br/>"));
            panel.ContentTemplateContainer.Controls.Add(
                new LiteralControl(""));
            panel.ContentTemplateContainer.Controls.Add(btnSelect);
            panel.ContentTemplateContainer.Controls.Add(
               new LiteralControl("&nbsp;&nbsp;"));
            panel.ContentTemplateContainer.Controls.Add(btnRemove);
            panel.ContentTemplateContainer.Controls.Add(
              new LiteralControl("<br/>"));
            

            panel.ContentTemplateContainer.Controls.Add(new LiteralControl(@"<tr><td><div
        class=""UserSectionHead"">Selected items:<br/>"));
            panel.ContentTemplateContainer.Controls.Add(lstSelectedItems);
            panel.ContentTemplateContainer.Controls.Add(
                new LiteralControl(@"</div></td></tr><tr><td>
            <div style=""width:100%"" class=""UserDottedLine""></div>
            </td></tr></table>"));

            Controls.Add(panel);

            base.CreateChildControls();
            //ViewState["Initialized"] = true;
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            SuppressWP part = WebPartToEdit as SuppressWP;
            if (part != null)
            {
                SuppressItemCollection selectedItems = new SuppressItemCollection();
                foreach (ListItem item in lstSelectedItems.Items)
                {
                    if(selectedItems.Any(p=>p.Name ==item.Value)) continue;
                    selectedItems.Add(Settings[item.Value]);

                }
                part.SuppressItems = selectedItems;
            }
            else { return false; }

            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            SuppressWP part = WebPartToEdit as SuppressWP;
            lstSelectedItems.Items.Clear();
            if (part != null && part.SuppressItems != null)
            {
                List<SuppressItem> items = part.SuppressItems.DistinctBy(p=>p.Name).ToList();
                foreach (var item in items)
                {
                    lstSelectedItems.Items.Add(item.Name);
                }
            }
        } 
        #endregion
    }
}
